// pages/notice/projectTeam/projectTeam.js
import throttle from '../../../utils/throttle.js';
import { hasPermission, subscribe } from '../../../utils/tools';
import { scrollToLeftEnd } from '../../../utils/behavior';
import Http from '../../../utils/http.js';
const http = new Http();
const app = getApp();
Page({
    behaviors: [scrollToLeftEnd],
    /**
     * 页面的初始数据
     */
    data: {
        tabsArr: ['项目通告', '互动问答'],
        currentTabIndex: 0,
        // 项目组唯一id
        id: '',
        // 项目组名称
        project: '',
        // 项目组logo
        avatar: '',
        // 组长名字
        leaderName: '',
        // 项目组成员
        memberNames: '',
        pageNo: 0,
        loading: false,
        loadingAll: false,
        // 项目通告
        noticeArr: [],
        // 项目通告总数
        total: 0,
        // 问题数组
        questionArr: [],
        // 问题分页
        questionPageNum: 0,
        // 互动问答列表loading
        questionLoading: false,
        questionloadingAll: false,
        // 互动问答总数
        questionTotal: 0,
        // 更多操作
        show: false,
        actions: [
            {
                id: '00',
                name: '编辑',
                color: '#333333',
            },
            {
                id: '01',
                name: '删除',
                color: '#ff455e',
            },
        ],
        activeNoticeId: '',
        activeQuestionId: '',
        // '00'是通告，'01'是问答
        flg: null,
        // 点击的通告
        clickNoticeIndex: null,
        clickNoticeId: '',
        // 点击的互动问答
        clickQuestionIndex: null,
        clickQuestionId: null,
        permissionList: ['00', '01'],
        // 项目组权限
        projectauthority: '',
        //项目组是否关注
        subscribeflg: '00',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 设置页面顶部title
        wx.setNavigationBarTitle({
            title: options.project,
        });

        this.setData({
            id: options.id,
            project: options.project,
        });

        this.getProjectTeamDetail(options.id);
        this.getProjectNoticeList();
        this.getProjectQuestionList();
    },

    onShow() {
        // 设置页面顶部title
        if (this.data.project) {
            wx.setNavigationBarTitle({
                title: this.data.project,
            });
        }
        // 修改导航栏颜色（为了适配安卓）
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
            animation: {
                duration: 300,
                timingFunc: 'easeIn',
            },
        });
    },

    // 获取顶部项目组详情
    getProjectTeamDetail(id) {
        let _that = this;
        let data = {
            authId: app.globalData.authId,
            id: id,
        };
        http.getRequest(`cjMap/getProjectTeamDetail`, data).then((res) => {
            if (res.status == 0) {
                let memberNamesArr = [];
                if (res.member) {
                    res.member.map((member) => {
                        memberNamesArr.push(member.realname);
                    });
                }
                _that.setData({
                    avatar: res.projectTeam.pjteamlogopicurl.replace(
                        /\/0_/,
                        '/1_'
                    ),
                    leaderName: res.leader[0].realname,
                    memberNames: memberNamesArr.length
                        ? '、' + memberNamesArr.join('、')
                        : memberNamesArr.join('、'),
                    project: res.projectTeam.pjteamname,
                    projectauthority: res.projectauthority || '',
                    subscribeflg: res.projectTeam.subscribeflg,
                });
            }
        });
    },

    // 获取所有项目通告
    getProjectNoticeList() {
        let _that = this;
        if (!_that.data.loadingAll && !_that.data.loading) {
            _that.setData({
                pageNo: _that.data.pageNo + 1,
                loading: true,
                loadingAll: false,
            });
            let data = {
                authId: app.globalData.authId,
                pjteamid: _that.data.id,
                pageSize: 20,
                pageNo: _that.data.pageNo,
            };
            http.getRequest(`cjMap/getProjectNoticeList`, data).then((res) => {
                if (res.status == 0) {
                    res.data.map((notice) => {
                        // 使用缩略图
                        notice.coverpicurl = notice.coverpicurl.replace(
                            /\/0_/,
                            '/1_'
                        );
                        // 格式化时间
                        notice.createtime = app.timeago(notice.createtime);
                        _that.data.noticeArr.push(notice);
                    });

                    _that.setData({
                        noticeArr: _that.data.noticeArr,
                        loading: false,
                        total: res.pager.totalRows,
                        ['tabsArr[0]']: `项目通告·${res.pager.totalRows}`,
                    });

                    if (res.pager.currentPage >= res.pager.totalPages) {
                        _that.setData({
                            loadingAll: true,
                        });
                    }
                } else {
                    _that.setData({
                        loadingAll: true,
                        loading: false,
                    });
                }
            });
        }
    },

    // 获取互动问答
    getProjectQuestionList() {
        let _that = this;
        if (!_that.data.questionloadingAll && !_that.data.questionLoading) {
            _that.setData({
                questionPageNum: _that.data.questionPageNum + 1,
                questionLoading: true,
                questionloadingAll: false,
            });
            let data = {
                authId: app.globalData.authId,
                pjteamid: _that.data.id,
                pageSize: 20,
                pageNo: _that.data.questionPageNum,
                createtimeorder: _that.data.best ? '' : 'desc',
                praisecntorder: _that.data.best ? 'desc' : '',
            };
            http.getRequest(`cjMap/getProjectQuestionList`, data).then(
                (res) => {
                    if (res.status == 0) {
                        res.data.map((question) => {
                            question.createtime = app.timeago(
                                question.createtime
                            );
                            _that.data.questionArr.push(question);
                        });
                        _that.setData({
                            questionArr: _that.data.questionArr,
                            questionLoading: false,
                            questionTotal: res.pager.totalRows,
                            ['tabsArr[1]']: `互动问答·${res.pager.totalRows}`,
                        });

                        if (res.pager.currentPage >= res.pager.totalPages) {
                            _that.setData({
                                questionloadingAll: true,
                            });
                        }
                    } else {
                        _that.setData({
                            questionloadingAll: true,
                            questionLoading: false,
                        });
                    }
                }
            );
        }
    },

    // 刷新通告
    refresh() {
        this.setData(
            {
                pageNo: 0,
                loading: false,
                loadingAll: false,
                noticeArr: [],
            },
            () => {
                this.getProjectNoticeList();
            }
        );
    },

    // 刷新问题
    refreshQuestion() {
        this.setData(
            {
                questionPageNum: 0,
                questionLoading: false,
                questionloadingAll: false,
                questionArr: [],
            },
            () => {
                this.getProjectQuestionList();
            }
        );
    },

    changeNav: throttle(
        function (e) {
            let { nav, index, id } = e.currentTarget.dataset;
            if (this.data.currentTabIndex === 0) {
                this.setData({
                    clickNoticeIndex: index,
                    clickNoticeId: id,
                });
            } else {
                this.setData({
                    clickQuestionIndex: index,
                    clickQuestionId: id,
                });
            }
            console.log(nav, index);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 发公告
    // 只有管理员以上，项目组组长组员可以发布
    publishNotice: throttle(
        function (e) {
            const { nav } = e.currentTarget.dataset;
            if (hasPermission(['00', '01']) || this.data.projectauthority) {
                wx.navigateTo({
                    url: nav,
                });
            } else {
                wx.showToast({
                    title: '暂无权限',
                    icon: 'none',
                    duration: 2000,
                });
            }
        },
        200,
        {
            trailing: false,
        }
    ),

    // 长按编辑
    edit(e) {
        let {
            id,
            createuid,
            flg,
            istop,
            projectauthority,
        } = e.currentTarget.dataset;
        let actions = [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ];

        if (flg === '00') {
            // 说明是通告
            // 管理员或者本人发的通告或者项目组组长（只有项目组组长和组员可以发通告）
            if (
                hasPermission(this.data.permissionList, createuid) ||
                projectauthority == '02'
            ) {
                // 修改导航栏颜色
                wx.setNavigationBarColor({
                    frontColor: '#000000',
                    backgroundColor: '#484848',
                    animation: {
                        duration: 300,
                        timingFunc: 'easeIn',
                    },
                });
                // 只有管理员/组长可以置顶
                if (
                    hasPermission(this.data.permissionList) ||
                    projectauthority == '02'
                ) {
                    if (istop == '01') {
                        actions.splice(0, 0, {
                            name: '取消置顶',
                            color: '#333333',
                            id: 4,
                        });
                    } else {
                        actions.splice(0, 0, {
                            name: '置顶',
                            color: '#333333',
                            id: 3,
                        });
                    }
                }
                this.setData({
                    show: true,
                    activeNoticeId: id,
                    flg: '00',
                    activeCreateUid: createuid,
                    actions,
                });
            } else {
                return;
            }
        } else {
            // 说明是问题
            // 互动问答是所有人可以发布，该项目组组长可以编辑
            if (
                hasPermission(this.data.permissionList, createuid) ||
                projectauthority == '02'
            ) {
                // 修改导航栏颜色
                wx.setNavigationBarColor({
                    frontColor: '#000000',
                    backgroundColor: '#484848',
                    animation: {
                        duration: 300,
                        timingFunc: 'easeIn',
                    },
                });
                this.setData({
                    show: true,
                    activeQuestionId: id,
                    flg: '01',
                    activeCreateUid: createuid,
                    actions,
                });
            } else {
                return;
            }
        }
        // 隐藏tabbar
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                tabbarShow: false,
            });
        }
    },

    // 取消编辑
    onCancel() {
        // 修改导航栏颜色
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
            animation: {
                duration: 300,
                timingFunc: 'easeIn',
            },
        });
        this.setData({
            show: false,
        });
    },

    // 选中后
    onSelect(e) {
        let _that = this;
        if (_that.data.flg === '00') {
            if (e.detail.id == 2) {
                wx.navigateTo({
                    url: `../../../releasePage/pages/announcePublish/announcePublish?noticeId=${_that.data.activeNoticeId}`,
                });
            } else if (e.detail.id == 1) {
                wx.showModal({
                    title: '确认删除？',
                    content: '',
                    success: function (res) {
                        if (res.confirm) {
                            _that.deleteNotice(_that.data.activeNoticeId);
                        } else {
                            console.log('取消操作');
                        }
                    },
                });
            } else if (e.detail.id == 3) {
                this.setProjectNoticeTop('01');
            } else if (e.detail.id == 4) {
                this.setProjectNoticeTop('00');
            }
        } else if (_that.data.flg === '01') {
            if (e.detail.id == 2) {
                wx.navigateTo({
                    url: `../../../releasePage/pages/publishQuestion/publishQuestion?questionId=${_that.data.activeQuestionId}`,
                });
            } else if (e.detail.id == 1) {
                wx.showModal({
                    title: '确认删除？',
                    content: '',
                    success: function (res) {
                        if (res.confirm) {
                            _that.deleteQuestion(_that.data.activeQuestionId);
                        } else {
                            console.log('取消操作');
                        }
                    },
                });
            }
        }
        this.onCancel();
    },

    deleteNotice(id) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/deleteProjectNotice',
            data: {
                authId: app.globalData.authId,
                id: id,
            },
            success(res) {
                if (res.data.status === '0') {
                    // 取消弹框
                    _that.onCancel();
                    // 删除成功后就刷新
                    _that.refresh();
                    let pages = getCurrentPages(); //当前页面栈
                    let prevPage = pages[pages.length - 2]; //上一页面（通告首页）
                    prevPage.refresh();

                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 1500,
                    });
                } else {
                    console.log('删除失败');
                }
            },
        });
    },

    deleteQuestion(id) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/deleteProjectQuestion',
            data: {
                authId: app.globalData.authId,
                id: id,
            },
            success(res) {
                if (res.data.status === '0') {
                    // 取消弹框
                    _that.onCancel();
                    // 删除成功后就刷新问题列表
                    _that.refreshQuestion();

                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 1500,
                    });
                } else {
                    console.log('删除失败');
                }
            },
        });
    },

    // 项目组内置顶
    setProjectNoticeTop(istop) {
        // '00'取消置顶 '01'设置置顶
        let data = {
            authId: app.globalData.authId,
            id: this.data.activeNoticeId,
            istop,
        };
        http.getRequest('cjMap/setProjectNoticeTop', data).then((res) => {
            if (res.status == '0') {
                this.refresh();
            }
        });
    },

    // 刷新文字变灰
    handleRead() {
        const property = `noticeArr[${this.data.clickNoticeIndex}].readflg`;
        this.setData({
            [property]: '01',
        });
        // 需要刷新通达页面的通告
        const pages = getCurrentPages(); //当前页面栈
        const prevPage = pages[pages.length - 3]; //上上一页面
        prevPage.data.noticeArr.map((item, index) => {
            if (item.id === this.data.clickNoticeId) {
                prevPage.setData({
                    [`noticeArr[${index}].readflg`]: '01',
                });
            }
        });
    },

    handleQuestionRead() {
        const property = `questionArr[${this.data.clickQuestionIndex}].readflg`;
        this.setData({
            [property]: '01',
        });
        // 需要刷新通达页面的通告
        const pages = getCurrentPages(); //当前页面栈
        const prevPage = pages[pages.length - 3]; //上上一页面
        prevPage.data.questionArr.map((item, index) => {
            if (item.id === this.data.clickQuestionId) {
                prevPage.setData({
                    [`questionArr[${index}].readflg`]: '01',
                });
            }
        });
    },

    onTabsClick(e) {
        this.setData({
            currentTabIndex: e.detail.index,
        });
    },

    swiperChange(e) {
        this.setData({
            currentTabIndex: e.detail.current,
        });
    },
    //关注
    subscribeBtn() {
        let _that = this;
        let flg = '00';
        if (_that.data.subscribeflg == '00') {
            flg = '01';
        } else {
            if (
                _that.data.projectauthority == '02' ||
                _that.data.projectauthority == '03'
            ) {
                wx.showToast({
                    title: '项目组成员不可以取消关注哦！',
                    icon: 'none',
                    duration: 2000,
                });
                return;
            }
        }
        subscribe(_that.data.id, flg, function () {
            wx.showToast({
                title: flg == '00' ? '已取消关注' : '关注成功',
                icon: 'none',
                duration: 2000,
            });
            _that.setData({
                subscribeflg: flg,
            });
        });
    },
});
